#include "CustomHeaderView.h"
#include <QApplication>
#include <QStyleOptionHeader>
#define FIRSTINDEX(index) index % 2 == 0 ? index : index - 1
#define SECONDINDEX(index) index % 2 == 0 ? index + 1 : index

CustomHeaderView::CustomHeaderView(Qt::Orientation orientation, QWidget *parent)
    : QHeaderView(orientation, parent)
{
    setStretchLastSection(false);
    setDefaultAlignment(Qt::AlignCenter);
    setHighlightSections(false);
    setSectionsClickable(false);
    setSectionsMovable(false);
}

void CustomHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
    if (!rect.isValid())
        return;

    painter->save();
    painter->setRenderHint(QPainter::Antialiasing);

    int cabinetNumber = (logicalIndex / 2) + 1;
    drawCabinetHeader(painter, cabinetNumber, FIRSTINDEX(logicalIndex), SECONDINDEX(logicalIndex));

    painter->restore();
}

QSize CustomHeaderView::sectionSizeFromContents(int logicalIndex) const
{
    Q_UNUSED(logicalIndex)
    return QSize(80, 50);
}

void CustomHeaderView::drawCabinetHeader(QPainter *painter, int cabinetNumber, int logicalIndex, int logicalIndex2) const
{
    int nextWidth = sectionSize(logicalIndex + 1);
    QRect wholeRect = QRect(sectionViewportPosition(logicalIndex), 0, sectionSize(logicalIndex) + sectionSize(logicalIndex2), height());
    painter->fillRect(wholeRect, Qt::black);
    QPen pen(QColor(255, 255, 17));
    painter->setPen(pen);
    QFont font = painter->font();
    font.setPointSize(22);
    font.setBold(true);
    painter->setFont(font);
    painter->drawText(wholeRect, Qt::AlignCenter, QString("%1柜").arg(cabinetNumber, 2, 10, QChar('0')));
    pen.setColor(QColor(255, 255, 255));
    painter->setPen(pen);
    painter->drawLine(wholeRect.right(), wholeRect.top(), wholeRect.right(), wholeRect.bottom());
    painter->drawLine(wholeRect.left(), wholeRect.top(), wholeRect.left(), wholeRect.bottom());
}
